package config

import (
	"fmt"

	"github.com/BurntSushi/toml"
)

// Config 对应配置文件结构
type Config struct {
	Listen    string              `toml:"listen"`
	DBServers map[string]DBServer `toml:"dbservers"`
}

// Validate 验证配置
func (c *Config) Validate() error {

	if c.Listen == "" {
		return fmt.Errorf("listen not config")
	}
	return nil
}

// UnmarshalConfig 解析toml配置
func UnmarshalConfig(tomlfile string) (*Config, error) {
	c := &Config{}
	if _, err := toml.DecodeFile(tomlfile, c); err != nil {
		return c, err
	}
	return c, nil
}

// GetListenAddr 监听地址
func (c Config) GetListenAddr() string {
	return c.Listen
}

// DBServer 表示DB服务器配置
type DBServer struct {
	Host     string `toml:"host"`
	Port     int    `toml:"port"`
	DBName   string `toml:"dbname"`
	User     string `toml:"user"`
	Password string `toml:"password"`
}

// DBServerConf 获取数据库配置
func (c Config) DBServerConf(key string) (DBServer, bool) {
	s, ok := c.DBServers[key]
	return s, ok
}

// ConnectString 表示连接数据库的字符串
func (m DBServer) ConnectString() string {
	//用户名:密码@(主机地址:端口)/数据库名称?charset=utf8&parseTime=True&loc=Local  mysql
	//host=%s port=%d user=%s password=%s dbname=%s sslmode=disable postgres _ "github.com/lib/pq"
	return fmt.Sprintf("%s:%s@(%s:%d)/%s?charset=utf8&parseTime=True&loc=Local",
		m.User, m.Password, m.Host, m.Port, m.DBName)
}
